use rusqlite::{Connection, Error, params, Result};

/// 自己通过mapdownloader下载的地图需要添加视图
// CREATE VIEW v_tiles AS SELECT
// t.zoom zoom_level,
// t.x tile_column,
// t.y tile_row,
// td.tile tile_data,
// t.type
// FROM
// 	Tiles t,
// 	TilesData td
// WHERE
// 	t.id = td.id;

/// 根据参数从mbtiles文件中查询一条数据，并返回
/// `tiles` mbtiles文件名
/// `z` 地图的zone
/// `x` 地图的x坐标
/// `y` 地图的y坐标
pub fn select_tile_data(name: &str, tiles: &str, z: i32, x: i32, y: i32) -> Result<Vec<u8>> {
    let conn = Connection::open(tiles)?;

    let config_tiles = &crate::server::CONFIG.tiles;
    let t = config_tiles
        .into_iter()
        .filter(|e| e.name == name)
        .collect::<Vec<&crate::info::Tiles>>();
    if t.len() > 0 {
        let map_type = &t.first().unwrap().map_type;
        let mut stmt;
        let mut yy = y;
        if map_type == "osm" {
            let base: i32 = 2;
            yy = (base.pow(z as u32) - 1) - y;
            stmt = conn.prepare("SELECT `tile_data` FROM `tiles` WHERE `zoom_level` = ? AND `tile_column` = ? AND `tile_row` = ? LIMIT 1")?;
        } else {
            stmt = conn.prepare("SELECT `tile_data` FROM `v_tiles` WHERE `zoom_level` = ? AND `tile_column` = ? AND `tile_row` = ? and type = 506225996 LIMIT 1")?;
        }
        let tile_data: Vec<u8> = stmt.query_row(params![z, x, yy], |row| {
            Ok(row.get(0)?)
        })?;

        Ok(tile_data)
    } else {
        Err(Error::ExecuteReturnedResults)
    }
}

pub fn select_tile_data_mark(name: &str, tiles: &str, z: i32, x: i32, y: i32) -> Result<Vec<u8>> {
    let conn = Connection::open(tiles)?;
    let mut stmt = conn.prepare("SELECT `tile_data` FROM `v_tiles` WHERE `zoom_level` = ? AND `tile_column` = ? AND `tile_row` = ? and type = 1882469030 LIMIT 1")?;

    let tile_data: Vec<u8> = stmt.query_row(params![z, x, y], |row| {
        Ok(row.get(0)?)
    })?;

    Ok(tile_data)
}
